<template>
  <div>
    <TopFilter ref="formpanel1" :list="formList1" labelWidth="100" :isSubmitBtn="true" @filterChange="formchangeFun" />
    <!-- <ButtonArea :style="{ paddingLeft: '300px' }">
      <el-button @click="FormPanelSeacher" type="primary">搜 索</el-button>
      <el-button @click="FormPanelreset">重置</el-button>
    </ButtonArea> -->
    <FilterTable
      ref="basetable"
      :columns="columns"
      columnsRef="partPartOutboundInternalReceiveAddNewPartPage"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns => (this.columns = columns)"
      :height="'200'"
      :dataSource="toptablelist"
      :onEnterEvent="tableDbclickFun"
      selectionType="single"
      :onRowSelectChange="selectTableFun"
    ></FilterTable>
    <FormPanel ref="formpanel2" :list="formList2" labelWidth="120" :isSubmitBtn="false" @formChange="formchangeFuns" />
    <FilterTable
      ref="basetables"
      :columns="columns1"
      columnsRef="partPartOutboundInternalReceiveAddNewPartPage1"
      :dataSource="emptyTableData"
      :params="fetchParams"
      :datakey="'rows'"
      :onColumnsChange="columns1 => (this.columns1 = columns1)"
      :height="'200'"
      :onSyncTableData="tablechangeFun"
    ></FilterTable>
    <div
      :style="{
        position: 'absolute',
        left: 0,
        bottom: 0,
        right: 0,
        zIndex: 9999,
        borderTop: '1px solid #e9e9e9',
        padding: '10px 20px',
        background: '#fff',
        textAlign: 'right'
      }"
    >
      <el-button @click="closeDialog">关 闭</el-button>
      <AjaxButton type="primary" :click="confirmHandle">保 存</AjaxButton>
    </div>
  </div>
</template>
<script>
import { dictionary } from '@/utils/dictMixin';
import { isAuthorized } from '@/utils/index';
import { getStorageList, getNewPartData, getaddPartList } from '@/api/part/partInventory/adjustInventory/index';
import { getStorage } from '@/api/part/partOutbound/internalReceive/index';
import { getAppId } from '@/assets/js/auth';
// import { getPinpSelect } from '@/api/repair/repairReception/customer';
import { getBrandList } from '@/api/common/cars/masterDataCars';
import { findAllRepair } from '@/api/repair/basicParameters';

export default {
  mixins: [dictionary],
  props: ['forReturn', 'ptype'],
  data() {
    this.basetable = null;
    this.basetables = null;
    return {
      formList1: this.createFrom(),
      formList2: this.createFroms(),
      fetchApi: getNewPartData,
      fetchParams: {
        xhrAbort: true
      },
      columns: this.createTable(),
      columns1: this.createTables(),
      emptyTableData: [], // 用于清空表格数据
      toptablelist: [],
      tableslist: [],
      storageData: {},
      fromSubmitdata: null,
      // 是否显示替换件按钮
      isreplace: true,
      replacedata: {},
      priceType: null
    };
  },
  created() {
    this.getlist();
  },
  mounted() {
    // this.checkAppId();
    this.basetable = this.$refs.basetable.$refs.pageTable;
    this.basetables = this.$refs.basetables.$refs.pageTable;
    // this.getPinpSelect();
    // this.findAllRepair();
    if (this.forReturn) {
      this.formList2.find(item => item.fieldName == 'OUT_QUANTITY').label = '退料数量';
      this.formList2.find(item => item.fieldName == 'SALES_PRICE').label = '退料单价';
      this.formList2.find(item => item.fieldName == 'SALES_AMOUNT').label = '退料金额';
    }
  },
  methods: {
    createFrom() {
      return [
        {
          type: 'SELECT',
          label: '仓库',
          fieldName: 'storageCode',
          itemList: []
        },
        // {
        //   type: 'SELECT',
        //   label: '品牌',
        //   fieldName: 'brand',
        //   itemList: []
        // },
        // {
        //   type: 'SELECT',
        //   label: '配件类别',
        //   fieldName: 'partGroupCode',
        //   itemList: this.createDictList('8075')
        // },
        {
          type: 'INPUT',
          label: '配件代码',
          fieldName: 'partNo'
        },
        // {
        //   type: 'INPUT',
        //   label: '拼音',
        //   fieldName: 'spellCode'
        // },
        {
          type: 'INPUT',
          label: '配件名称',
          fieldName: 'partName'
        }
        // {
        //   type: 'INPUT',
        //   label: '库位',
        //   fieldName: 'storagePositionCode'
        // },
        // {
        //   type: 'CHECKBOX',
        //   label: '库存大于零',
        //   fieldName: 'isCheck',
        //   initialValue: '10041001',
        //   options: { trueValue: '10041001', falseValue: '10041002' }
        // }
        // {
        //   type: 'CHECKBOX',
        //   label: '售价大于零',
        //   fieldName: 'isSalePriceBigger',
        //   options: { trueValue: '10041001', falseValue: '10041002' }
        // },
        // {
        //   type: 'INPUT',
        //   label: '备注',
        //   fieldName: 'remark'
        // }
      ];
    },
    createTable() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '仓库',
          dataIndex: 'STORAGE_NAME',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '库位',
          dataIndex: 'STORAGE_POSITION_CODE',
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件代码',
          dataIndex: 'PART_NO',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        {
          title: '配件名称',
          dataIndex: 'PART_NAME',
          showOverflowTooltip: true,
          sorter: true,
          filter: true,
          filterType: 'input'
        },
        // {
        //   title: '含税销售价',
        //   dataIndex: 'SALES_PRICE',
        //   sorter: true,
        //   filter: true,
        //   filterType: 'number',
        //   precision: 2
        // },
        {
          title: '含税成本价',
          dataIndex: 'COST_PRICE',
          sorter: true,
          filter: true,
          filterType: 'number',
          precision: 2
        },
        {
          title: '可用库存',
          dataIndex: 'USEABLE_STOCK',
          sorter: true,
          filter: true,
          precision: 2,
          filterType: 'number'
        },
        {
          title: '账面库存',
          dataIndex: 'STOCK_QUANTITY',
          sorter: true,
          precision: 2,
          filter: true,
          filterType: 'number'
        },
        {
          title: '备注',
          dataIndex: 'REMARK',
          sorter: true,
          filter: true,
          filterType: 'input'
        }
      ];
    },
    createFroms() {
      return [
        { type: 'SELECT', label: '仓库', fieldName: 'STORAGE_CODE', itemList: [], rules: [{ required: true, message: '请输入仓库', trigger: 'blur' }], disabled: true },
        { type: 'INPUT', label: '配件代码', fieldName: 'PART_NO', rules: [{ required: true, message: '请输入配件代码', trigger: 'blur' }], disabled: true },
        { type: 'INPUT', label: '配件名称', fieldName: 'PART_NAME', disabled: true },
        {
          type: 'INPUT_NUMBER',
          label: '出库数量',
          min: 0.01,
          precision: 2,
          fieldName: 'OUT_QUANTITY',
          change: val => {
            this.changemNum(val);
          },
          rules: [{ required: true, message: '请输入出库数量', trigger: 'blur' }],
          disabled: false
        },
        {
          type: 'INPUT_NUMBER',
          label: '出库单价',
          min: 0.0,
          precision: 2,
          hidden: true,
          fieldName: 'SALES_PRICE',
          change: val => {
            this.changemoney(val);
          },
          rules: [{ required: true, message: '请输入出库单价', trigger: 'blur' }],
          disabled: false
        },
        { type: 'INPUT_NUMBER', label: '出库金额', hidden: true, precision: 2, fieldName: 'SALES_AMOUNT', rules: [{ required: true, message: '请输入出库金额', trigger: 'blur' }], disabled: true }
      ];
    },
    createTables() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        // { title: '含税销售价', dataIndex: 'SALES_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '终端建议零售VIP价格', dataIndex: 'NOT_TAX_INSTRUCT_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '常规订货价', dataIndex: 'PLAN_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '成本单价', dataIndex: 'COST_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '索赔价', dataIndex: 'CLAIM_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number', hidden: !isAuthorized('1313', '13131006') },
        { title: '终端建议零售价格', dataIndex: 'INSURANCE_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        // { title: '最低销售限价', dataIndex: 'MIN_LIMIT_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        // { title: '销售限价', dataIndex: 'LIMIT_PRICE', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '最大库存', dataIndex: 'MAX_STOCK', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '最小库存', dataIndex: 'MIN_STOCK', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '账面库存', dataIndex: 'STOCK_QUANTITY', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '可用库存', dataIndex: 'USEABLE_STOCK', precision: 2, sorter: true, filter: true, filterType: 'number' },
        // { title: '借进数量', dataIndex: 'BORROW_QUANTITY', sorter: true, filter: true, filterType: 'input' },
        // { title: '借出数量', dataIndex: 'LEND_QUANTITY', sorter: true, filter: true, filterType: 'input' },
        { title: '锁定量', dataIndex: 'LOCKED_QUANTITY', precision: 2, sorter: true, filter: true, filterType: 'number' },
        { title: '替代配件', dataIndex: 'OPTION_NO', sorter: true, filter: true, filterType: 'input' },
        { title: '替代件库存', dataIndex: 'OPTION_STOCK', precision: 2, sorter: true, filter: true, filterType: 'number' },
        {
          title: '配件类别',
          dataIndex: 'PART_GROUP_CODE',
          sorter: true,
          filter: true,
          filterType: 'checkbox',
          filterItems: this.createDictList('8247'),
          dictItems: this.createDictList('8247')
        },
        { title: '单位', dataIndex: 'UNIT_NAME', sorter: true, filter: true, filterType: 'input' }
      ];
    },
    // 获取数据字典数据
    async getlist() {
      let res = await getStorage({});
      this.storageData = res.data;
      // this.formList1[0].itemList = (await getStorageList({})).data.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.formList1.find(x => x.fieldName === 'storageCode').itemList = this.storageData.map(x => ({ text: x.STORAGE_NAME, value: x.STORAGE_CODE }));
      this.formList2[0].itemList = this.formList1.find(x => x.fieldName === 'storageCode').itemList;
    },

    // 获取品牌下拉框
    async getPinpSelect() {
      const res = await getBrandList();
      this.formList1.find(x => x.fieldName === 'brand').itemList = res.data.map(x => ({ value: x.brandCode + '', text: x.brandName }));
      this.formList1.find(x => x.fieldName === 'brand').initialValue = res.data.find(item => item.brandName == '奥迪').brandCode + '';
    },

    //  获取系统参数
    async findAllRepair() {
      const res = await findAllRepair();
      // console.log(res, 'resss');
      this.priceType = res.data['1061'];
      this.formList1.find(item => item.fieldName === 'storageCode').initialValue = res.data['1100'];
      // this.formList1.find(x => x.fieldName === 'storageCode').initialValue = res.data['1100'];
      console.log(this.priceType, 'priceType');
    },

    // 重置
    FormPanelreset() {
      this.$refs.formpanel1.RESET_FORM();
    },
    FormPanelSeacher() {
      this.$refs.formpanel1.SUBMIT_FORM();
      this.$refs.formpanel2.RESET_FORM();
      this.emptyTableData = [];
    },
    // 选中事件
    selectTableFun(val) {
      if (val && val.length > 0) {
        let value = val[0].OPTION_NO;
        this.replacedata = val[0];
        if (value == null) {
          this.isreplace = true;
        } else {
          this.isreplace = false;
        }
      }
    },
    formchangeFun(val) {
      this.fetchParams.xhrAbort = true;
      this.fetchParams = Object.assign(this.fetchParams, val, { xhrAbort: false });
    },
    formchangeFuns(val) {
      console.log(val, 'formchangeFuns');
      this.fromSubmitdata = val; // {...val};
    },
    tableDbclickFun(val) {
      console.log(val, '双击');
      // this.tablelist = val;
      this.formList2.find(item => item.fieldName == 'STORAGE_CODE').initialValue = val.STORAGE_CODE;
      this.formList2.find(item => item.fieldName == 'PART_NO').initialValue = val.PART_NO;
      this.formList2.find(item => item.fieldName == 'PART_NAME').initialValue = val.PART_NAME;
      this.formList2.find(item => item.fieldName == 'OUT_QUANTITY').initialValue = 1.0;
      this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.COST_PRICE;
      // this.formList2[4].initialValue = val.SALES_PRICE;
      // this.formList2[5].initialValue = val.SALES_PRICE;
      // 出库价=成本价
      if (this.priceType === '80501001') {
        if (val.COST_PRICE == '' || val.COST_PRICE == null || val.COST_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.COST_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501002') {
        if (val.SALES_PRICE == '' || val.SALES_PRICE == null || val.SALES_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.SALES_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501003') {
        if (val.CLAIM_PRICE == '' || val.CLAIM_PRICE == null || val.CLAIM_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.CLAIM_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501004') {
        if (val.NODE_PRICE == '' || val.NODE_PRICE == null || val.NODE_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.NODE_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501005') {
        if (val.LATEST_PRICE == '' || val.LATEST_PRICE == null || val.LATEST_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.LATEST_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501006') {
        this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
      } else if (this.priceType === '80501007') {
        if (val.INSURANCE_PRICE == '' || val.INSURANCE_PRICE == null || val.INSURANCE_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.INSURANCE_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501008') {
        if (val.INSTRUCT_PRICE == '' || val.INSTRUCT_PRICE == null || val.INSTRUCT_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.INSTRUCT_PRICE.toFixed(2);
        }
      } else if (this.priceType === '80501009') {
        if (val.LIMIT_PRICE == '' || val.LIMIT_PRICE == null || val.LIMIT_PRICE == undefined) {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = 0.0;
        } else {
          this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue = val.LIMIT_PRICE.toFixed(2);
        }
      }
      this.formList2.find(item => item.fieldName == 'SALES_AMOUNT').initialValue = (this.formList2.find(item => item.fieldName == 'SALES_PRICE').initialValue * 1).toFixed(2);
      // this.formList2[0].initialValue=val.SALES_PRICE;
      // this.formList2[0].initialValue=val.STORAGE_CODE;
      // this.formList2[0].initialValue=val.STORAGE_CODE;
      console.log('***', this.formList2);
      this.getpartlist(val);
    },
    async getpartlist(val) {
      this.emptyTableData = [];
      let res = (await getaddPartList(val.STORAGE_CODE, val.PART_NO)).data.rows;
      this.basetables.EXECUTE_INSERT(res);
    },
    changemoney(val) {
      console.log(val, 'input');
      let num = this.formList2[3].initialValue;
      this.formList2[5].initialValue = val * num;
    },
    changemNum(val) {
      console.log(val, '改变');
      let money = this.formList2[4].initialValue;
      this.formList2[5].initialValue = val * money;
    },
    // 关闭弹窗
    closeDialog() {
      this.$emit('close', false);
    },
    tablechangeFun(val) {
      console.log(val);
      this.tableslist = val;
    },
    // 添加事件提交表单
    confirmHandle() {
      this.fromSubmitdata = null;
      this.$refs.formpanel2.SUBMIT_FORM();
      if (this.fromSubmitdata != null) {
        let json = this.tableslist[0];
        this.$refs.formpanel2.SUBMIT_FORM();
        var flag = 2; // 是否记录缺料信息1为是，2为否
        if (this.forReturn) {
          // 退料
          json.OUT_QUANTITY = this.fromSubmitdata.OUT_QUANTITY * -1;
          json.OUT_PRICE = this.fromSubmitdata.SALES_PRICE;
          json.OUT_AMOUNT = this.fromSubmitdata.SALES_AMOUNT * -1;
          json.COST_PRICE = Number(json.COST_PRICE).toFixed(2);
          json.COST_AMOUNT = (json.COST_PRICE * this.fromSubmitdata.OUT_QUANTITY * -1).toFixed(2);
          json.ITEM_ID = '';
        } else {
          // 新增
          json.OUT_QUANTITY = this.fromSubmitdata.OUT_QUANTITY;
          json.OUT_PRICE = this.formList2.find(x => x.fieldName == 'SALES_PRICE').initialValue;
          json.OUT_AMOUNT = this.formList2.find(x => x.fieldName == 'SALES_AMOUNT').initialValue;
          json.COST_PRICE = Number(json.COST_PRICE).toFixed(2);
          json.COST_AMOUNT = (json.COST_PRICE * this.fromSubmitdata.OUT_QUANTITY).toFixed(2);
          json.ITEM_ID = '';
        }

        // if(this.fromSubmitdata.SALES_PRICE<json.COST_PRICE){
        //     this.$notify({ title: '警告信息', message: '配件销售单价小于成本单价！', type: 'warning' });
        //     return;
        // }
        if (!this.forReturn && this.fromSubmitdata.OUT_QUANTITY > json.USEABLE_STOCK) {
          // for (var i = 0; i < this.storageData.length; i++) {
          //   if (this.storageData[i].STORAGE_CODE == this.formList2[0].initialValue) {
          //     if (this.storageData[i].IS_NEGATIVE == 10041002) {
          //       this.$notify({ title: '警告信息', message: '出库数量大于可用数量，该仓库不允许负库存，不可以出库！', type: 'warning' });
          //       return;
          //     }
          //   }
          // }
          this.$confirm('是否记录缺料明细？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
            .then(async () => {
              flag = 1;
              json.FLAG = flag;
              let formdata = Object.assign({}, json);
              this.$emit('addNewPart', formdata);
            })
            .catch(() => {
              flag = 2;
              json.FLAG = flag;
              let formdata = Object.assign({}, json);
              this.$emit('addNewPart', formdata);
            });
        } else {
          json.FLAG = flag;
          let formdata = Object.assign({}, json);
          this.$emit('addNewPart', formdata);
        }
      }
    },
    async checkAppId() {
      let appId = await getAppId();
      if (appId == 'beijing') {
        this.formList2.find(x => x.fieldName == 'SALES_PRICE').hidden = true;
        this.formList2.find(x => x.fieldName == 'SALES_AMOUNT').hidden = true;
      }
    },
    // 获取系统权限
    getAuthority() {
      if (this.forReturn === '内部领用新增') {
        if (isAuthorized('1313', '13131005')) {
          this.columns.find(x => x.dataIndex === 'COST_PRICE').hidden = false;
        } else {
          this.columns.find(x => x.dataIndex === 'COST_PRICE').hidden = false;
        }
      }
    }
  }
};
</script>
